package com.hsy.linemoney.modules.exchange;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.deparse.dpframe.tools.utils.DPGsonUtil;
import com.deparse.dpframe.tools.utils.DPLogUtil;
import com.hsy.linemoney.R;
import com.hsy.linemoney.apiservice.CalculateService;
import com.hsy.linemoney.apiservice.Callback;
import com.hsy.linemoney.apiservice.CurrencyService;
import com.hsy.linemoney.apiservice.ExchangeService;
import com.hsy.linemoney.apiservice.LineMoneyContext;
import com.hsy.linemoney.apiservice.ServiceTypeService;
import com.hsy.linemoney.modules.common.CommonBaseFragment;
import com.hsy.linemoney.modules.common.HowToSaveDialog;
import com.hsy.linemoney.modules.common.StepView;
import com.hsy.linemoney.modules.main.MainActivity;
import com.hsy.linemoney.utils.CommonUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;

/**
 * Created by Administrator on 2016/6/23.
 */
public class ExchangeOnceFragment extends CommonBaseFragment implements View.OnClickListener {

    protected StepView stepView;
    protected LinearLayout resultPanel;

    protected TextView leftPrice;
    protected TextView leftUnit;
    protected TextView rightPrice;
    protected TextView rightUnit;
    protected TextView fromTypeSpinner;
    protected TextView toTypeSpinner;
    protected EditText exchangeAmount;
    protected CheckBox useMarketRate;
    protected EditText expectedRate;
    protected TextView service_type;
    protected TextView estimatedAmountPrice;
    protected TextView estimatedAmountUnit;
    protected TextView exechangeCostPrice;
    protected TextView exechangeCostUnit;
    protected TextView bankRate;
    protected TextView weSavedPrice;
    protected TextView weSavedUnit;
    protected TextView howToSave;
    protected TextView nextStep;

    private ViewStub viewStub;
    private boolean isInflated = false;
    private boolean isInflating = false;

    private CurrencyService.CurrencyListResult mCurrencyListResult;
    private int leftWitch = -1, rightWitch = -1;

    private ViewStub.OnInflateListener onInflateListener = new ViewStub.OnInflateListener() {
        @Override
        public void onInflate(ViewStub stub, View inflated) {
            initView(inflated);
            isInflated = true;
        }
    };
    private ViewGroup expectedRateContainer;
    private ViewGroup formContainer;
    private int serviceTypeWhitch = -1;
    private ServiceTypeService.ServiceTypeListResult mServiceTypeListResult;

    @Override
    protected int getFragmentLayout() {
        return R.layout.fragment_exchange_once;
    }

    @Override
    protected void initView(View view, Bundle bundle) {
        showProgressDialog(getAttchedActivity());
        viewStub = findViewById(R.id.view_stub);
        viewStub.setOnInflateListener(onInflateListener);
        removeMessages(1);
        sendEmptyMessageDelayed(1, 500);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && !isInflating && !isInflated) {
            isInflating = true;
//            sendEmptyMessageDelayed(0, 50);
            sendEmptyMessage(0);
        }
    }

    private CalculateService.CalculateResult mCalculateResult;

    private void initView(View rootView) {
        getRootView().setVisibility(View.GONE);

        leftPrice = (TextView) rootView.findViewById(R.id.left_price);
        leftUnit = (TextView) rootView.findViewById(R.id.left_unit);
        rightPrice = (TextView) rootView.findViewById(R.id.right_price);
        rightUnit = (TextView) rootView.findViewById(R.id.right_unit);
        fromTypeSpinner = (TextView) rootView.findViewById(R.id.from_type_spinner);
        fromTypeSpinner.setOnClickListener(ExchangeOnceFragment.this);
        toTypeSpinner = (TextView) rootView.findViewById(R.id.to_type_spinner);
        toTypeSpinner.setOnClickListener(ExchangeOnceFragment.this);
        exchangeAmount = (EditText) rootView.findViewById(R.id.exchange_amount);
        useMarketRate = (CheckBox) rootView.findViewById(R.id.use_market_rate);
        expectedRate = (EditText) rootView.findViewById(R.id.expected_rate);
        service_type = (TextView) rootView.findViewById(R.id.service_type);
        expectedRateContainer = (ViewGroup) rootView.findViewById(R.id.expected_rate_container);
        estimatedAmountPrice = (TextView) rootView.findViewById(R.id.estimated_amount_price);
        estimatedAmountUnit = (TextView) rootView.findViewById(R.id.estimated_amount_unit);
        exechangeCostPrice = (TextView) rootView.findViewById(R.id.exechange_cost_price);
        exechangeCostUnit = (TextView) rootView.findViewById(R.id.exechange_cost_unit);
        bankRate = (TextView) rootView.findViewById(R.id.bank_rate);
        weSavedPrice = (TextView) rootView.findViewById(R.id.we_saved_price);
        weSavedUnit = (TextView) rootView.findViewById(R.id.we_saved_unit);
        howToSave = (TextView) rootView.findViewById(R.id.how_to_save);
        howToSave.setOnClickListener(ExchangeOnceFragment.this);
        nextStep = (TextView) rootView.findViewById(R.id.next_step);
        nextStep.setOnClickListener(ExchangeOnceFragment.this);
        stepView = (StepView) rootView.findViewById(R.id.step_view);
        resultPanel = (LinearLayout) rootView.findViewById(R.id.result_panel);
        formContainer = (ViewGroup) rootView.findViewById(R.id.form_container);

        service_type.setOnClickListener(this);

        exchangeAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (null == s || 0 == s.length()) {
//                    resultPanel.setVisibility(View.GONE);
                } else {
                    mCalculateResult = null;
                    removeMessages(1);
                    sendEmptyMessageDelayed(1, 500);
                }
            }
        });
        exchangeAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus && useMarketRate.isChecked()) {
                    removeMessages(1);
                    sendEmptyMessage(1);
                }
            }
        });
        expectedRate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (null == s || 0 == s.length()) {
//                    resultPanel.setVisibility(View.GONE);
                } else {
                    mCalculateResult = null;
                    removeMessages(1);
                    sendEmptyMessageDelayed(1, 500);
                }
            }
        });
        expectedRate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    removeMessages(1);
                    sendEmptyMessage(1);
                }
            }
        });
        useMarketRate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                DPLogUtil.d("onCheckedChanged");
//                expectedRateContainer.setVisibility(isChecked ? View.GONE : View.VISIBLE);
//                formContainer.measure(0, 0);
                expectedRate.setEnabled(!isChecked);
//                service_type.setEnabled(!isChecked);

                mCalculateResult = null;
                removeMessages(1);
                sendEmptyMessageDelayed(1, 500);
            }
        });

        CalculateService service = new CalculateService();
        service.calculate("USD", "CNY", "1", "0", "ServiceType_101", "0", new Callback<CalculateService.CalculateResult>() {
            @Override
            public void onSuccess(int what, CalculateService.CalculateResult result) {
                rightPrice.setText(result.getData().getLmData().getLinemoneyRate());
                hideProgressDialog();
            }

            @Override
            public void onError(int what, int type, String msg, Exception e) {
                hideProgressDialog();
            }
        });

        CurrencyService currencyService = new CurrencyService();
        currencyService.getCurrency(new Callback<CurrencyService.CurrencyListResult>() {
            @Override
            public void onSuccess(int what, CurrencyService.CurrencyListResult result) {
                ExchangeOnceFragment.this.mCurrencyListResult = result;

                leftWitch = ((MainActivity) getAttchedActivity()).getExchangeFrom();
                rightWitch = ((MainActivity) getAttchedActivity()).getExchangeTo();
                if (-1 != leftWitch && -1 != rightWitch) {
                    fromTypeSpinner.setText(mCurrencyListResult.getCurrency().get(leftWitch).getDescription());
                    toTypeSpinner.setText(mCurrencyListResult.getCurrency().get(rightWitch).getDescription());
                    exchangeAmount.setText(((MainActivity) getAttchedActivity()).getExchangeAmount());
                } else if (mCurrencyListResult.getCurrency().size() > 1) {
                    leftWitch = 1;
                    rightWitch = 0;
                    fromTypeSpinner.setText(getCurrency(leftWitch).getDescription());
                    toTypeSpinner.setText(getCurrency(rightWitch).getDescription());
                }
                hideProgressDialog();
            }

            @Override
            public void onError(int what, int type, String msg, Exception e) {
                hideProgressDialog();
            }
        });

        new CurrencyService().getCurrency(new Callback<CurrencyService.CurrencyListResult>() {
            @Override
            public void onSuccess(int what, CurrencyService.CurrencyListResult result) {
                ExchangeOnceFragment.this.mCurrencyListResult = result;
                ServiceTypeService service = new ServiceTypeService();
                service.getServiceTypeList(new Callback<ServiceTypeService.ServiceTypeListResult>() {
                    @Override
                    public void onSuccess(int what, final ServiceTypeService.ServiceTypeListResult result) {
                        ExchangeOnceFragment.this.mServiceTypeListResult = result;
                        getRootView().setVisibility(View.VISIBLE);
                        hideProgressDialog();
                    }

                    @Override
                    public void onError(int what, int type, String msg, Exception e) {
                        showToast(R.string.txt_page_load_failure);
                        hideProgressDialog();
                    }
                });
            }

            @Override
            public void onError(int what, int type, String msg, Exception e) {
                showToast(R.string.txt_page_load_failure);
                hideProgressDialog();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onHandleMessage(Message message) {
        if (0 == message.what) {
            if (isInflating && !isInflated) {
                viewStub.inflate();
            }
        } else if (1 == message.what) {
            CalculateService service = new CalculateService();
            final String source, target, sourceUnit, targetUnit;
            source = mCurrencyListResult.getCurrency().get(leftWitch).getCurrencyCd();
            sourceUnit = mCurrencyListResult.getCurrency().get(leftWitch).getDescription();
            target = mCurrencyListResult.getCurrency().get(rightWitch).getCurrencyCd();
            targetUnit = mCurrencyListResult.getCurrency().get(rightWitch).getDescription();
            final String send = TextUtils.isEmpty(exchangeAmount.getText().toString()) ? "0" : exchangeAmount.getText().toString();
            final String serviceType = serviceTypeWhitch < 0 ? "ServiceType_101" : mServiceTypeListResult.getServiceTypes().get(serviceTypeWhitch).getServiceTypeCd();
            final String userRate = !useMarketRate.isChecked() && !TextUtils.isEmpty(expectedRate.getText().toString()) ? expectedRate.getText().toString() : "0";
            service.calculate(source, target, send, "0", serviceType, userRate, new Callback<CalculateService.CalculateResult>() {
                @Override
                public void onSuccess(int what, CalculateService.CalculateResult result) {
                    ExchangeOnceFragment.this.mCalculateResult = result;

                    double amount = Double.valueOf(send);
                    double lmfee = Double.valueOf(mCalculateResult.getData().getLmData().getLinemoneyTransferFee());
                    double bkfee = Double.valueOf(mCalculateResult.getData().getBankData().getBankTransferFee());
                    double lmrate = Double.valueOf(mCalculateResult.getData().getLmData().getLinemoneyRate());
                    double bkrate = Double.valueOf(mCalculateResult.getData().getBankData().getBankRate());

                    if (!useMarketRate.isChecked()) {
                        lmrate = TextUtils.isEmpty(expectedRate.getText().toString()) ? 0 : Double.valueOf(expectedRate.getText().toString());
                    }

                    double lmpayout = Double.valueOf(mCalculateResult.getData().getLmData().getLinemoneyPayOut());
                    double bkpayout = Double.valueOf(mCalculateResult.getData().getBankData().getBankPayOut());

                    estimatedAmountPrice.setText(String.format(LineMoneyContext.getLocalLanguagePair().locale, "%.2f", lmpayout));
                    estimatedAmountUnit.setText(targetUnit);
                    exechangeCostPrice.setText(String.format(LineMoneyContext.getLocalLanguagePair().locale, "%.2f", lmfee));
                    exechangeCostUnit.setText(sourceUnit);
                    bankRate.setText(String.format(LineMoneyContext.getLocalLanguagePair().locale, "%.4f", bkrate));
                    weSavedPrice.setText(String.format(LineMoneyContext.getLocalLanguagePair().locale, "%.2f", lmpayout - bkpayout));
                    weSavedUnit.setText(targetUnit);
                    resultPanel.setVisibility(View.VISIBLE);
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {
                    hideProgressDialog();
                }
            });
        }
    }

    @Override
    public void onFragmentUpdate() {

    }

    private String[] currencyArray;

    public String[] getCurrencyArray() {
        if (null == mCurrencyListResult) {
            return null;
        }
        if (null == currencyArray) {
            currencyArray = new String[mCurrencyListResult.getCurrency().size()];
            for (int i = 0; i < currencyArray.length; i++) {
                currencyArray[i] = mCurrencyListResult.getCurrency().get(i).getDescription();
            }
        }
        return currencyArray;
    }

    public CurrencyService.CurrencyListResult.Currency getCurrency(int which) {
        if (null == mCurrencyListResult) {
            return null;
        }
        return mCurrencyListResult.getCurrency().get(which);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.from_type_spinner) {
            CommonUtils.showListDialog(getAttchedActivity(), getCurrencyArray(), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    leftWitch = which;
                    rightWitch = 1 - which;
                    fromTypeSpinner.setText(getCurrencyArray()[which]);
                    toTypeSpinner.setText(getCurrencyArray()[rightWitch]);
                    dialog.dismiss();

                    mCalculateResult = null;
                    removeMessages(1);
                    sendEmptyMessageDelayed(1, 500);
                }
            });
        } else if (view.getId() == R.id.to_type_spinner) {
            CommonUtils.showListDialog(getAttchedActivity(), getCurrencyArray(), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    rightWitch = which;
                    leftWitch = 1 - which;
                    toTypeSpinner.setText(getCurrencyArray()[which]);
                    fromTypeSpinner.setText(getCurrencyArray()[1 - which]);
                    dialog.dismiss();

                    mCalculateResult = null;
                    removeMessages(1);
                    sendEmptyMessageDelayed(1, 500);
                }
            });
        } else if (view.getId() == R.id.how_to_save) {
            if (null != mCalculateResult) {
                HowToSaveDialog.HowToSaveDialogData data = new HowToSaveDialog.HowToSaveDialogData();
                data.setLinemoneyPayOut(mCalculateResult.getData().getLmData().getLinemoneyPayOut());
                data.setLinemoneyPayOutUnit(toTypeSpinner.getText().toString());
//                data.setLinemoneyRate(mCalculateResult.getData().getLmData().getLinemoneyRate());
                data.setLinemoneyRate(rightPrice.getText().toString());
                data.setLinemoneyTransferFee(mCalculateResult.getData().getLmData().getLinemoneyTransferFee());
                data.setLinemoneyTransferFeeUnit(fromTypeSpinner.getText().toString());

                data.setBankPayOut(mCalculateResult.getData().getBankData().getBankPayOut());
                data.setBankPayOutUnit(toTypeSpinner.getText().toString());
                data.setBankRate(mCalculateResult.getData().getBankData().getBankRate());
                data.setBankTransferFee(mCalculateResult.getData().getBankData().getBankTransferFee());
                data.setBankTransferFeeUnit(fromTypeSpinner.getText().toString());

                new HowToSaveDialog(getActivity(), data).show();
            }
        } else if (view.getId() == R.id.next_step) {
            if (checkThrought()) {
                ExchangeVerified verified = new ExchangeVerified();
                verified.setUserId(LineMoneyContext.getLoggedUser().getUserId());
                verified.setFromAmount(exchangeAmount.getText().toString());
                verified.setFromCurrencyCd(mCurrencyListResult.getCurrency().get(leftWitch).getCurrencyCd());
                ExchangeService service = new ExchangeService();
                try {
                    JSONObject params = new JSONObject(DPGsonUtil.toJson(verified));
                    service.verified(params, new Callback<JSONArray>() {
                        @Override
                        public void onSuccess(int what, JSONArray result) {
                            DPLogUtil.d(result.toString());
                            JSONObject status = result.optJSONObject(0).optJSONObject("status");
                            if ("200".equals(status.optString("code"))) {
                                toStep2();
                            } else {
                                DPLogUtil.d("verified fail");
                                AlertDialog.Builder builder = new AlertDialog.Builder(getAttchedActivity())
                                        .setMessage(status.optString("message"))
                                        .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                startActivity(ExchangeVerifiedFailActivity.class);
                                                dialog.dismiss();
                                            }
                                        }).setCancelable(false);
                                builder.show();
                            }
                        }

                        @Override
                        public void onError(int what, int type, String msg, Exception e) {

                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else if (view.getId() == R.id.service_type) {
            ServiceTypeService service = new ServiceTypeService();
            service.getServiceTypeList(new Callback<ServiceTypeService.ServiceTypeListResult>() {
                @Override
                public void onSuccess(int what, final ServiceTypeService.ServiceTypeListResult result) {
                    ExchangeOnceFragment.this.mServiceTypeListResult = result;
                    CommonUtils.showListDialog(getAttchedActivity(), null, result.getServiceNameArray(), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            serviceTypeWhitch = which;
                            service_type.setText(result.getServiceNameArray()[which]);
                            dialog.dismiss();
                            removeMessages(1);
                            sendEmptyMessage(1);
                        }
                    });
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {

                }
            });
        }
    }

    private boolean checkThrought() {

        if (TextUtils.isEmpty(exchangeAmount.getText().toString())) {
            showToast(R.string.txt_please_input_exchange_amount);
            return false;
        }

        if (!useMarketRate.isChecked() && TextUtils.isEmpty(expectedRate.getText().toString())) {
            showToast(R.string.txt_please_input_expected_rate);
            return false;
        }

//        if (null == mServiceTypeListResult || serviceTypeWhitch < 0) {
//            showToast(R.string.txt_please_select_service_type);
//            return false;
//        }

        return true;
    }

    private void toStep2() {
        ExchangeOnceOrderParamsData data = new ExchangeOnceOrderParamsData();
        data.setFromCurrencyCd(mCurrencyListResult.getCurrency().get(leftWitch).getCurrencyCd());
        data.setFromCurrencyCdUnit(mCurrencyListResult.getCurrency().get(leftWitch).getDescription());
        data.setToCurrencyCd(mCurrencyListResult.getCurrency().get(rightWitch).getCurrencyCd());
        data.setToCurrencyCdUnit(mCurrencyListResult.getCurrency().get(rightWitch).getDescription());
        data.setFromAmount(exchangeAmount.getText().toString());
        data.setFxRate(data.isUseMarketRate() || TextUtils.isEmpty(expectedRate.getText().toString()) ? "0" : expectedRate.getText().toString());
        data.setUseMarketRate(useMarketRate.isChecked());
        if (useMarketRate.isChecked()) {
            data.setServiceTypeCd(mServiceTypeListResult.getServiceTypes().get(0).getServiceTypeCd());
            DPLogUtil.d("useMarketRate.isChecked()==0");
        } else {
            data.setServiceTypeCd(mServiceTypeListResult.getServiceTypes().get(1).getServiceTypeCd());
            DPLogUtil.d("useMarketRate.isChecked()==1");
        }
        startActivity(ExchangeStep2Activity.class, DPGsonUtil.toJson(data), DPGsonUtil.toJson(mCalculateResult));
    }
}
